package com.smart.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.pojo.ResultBean;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class AuthenticationFormConfig extends FormAuthenticationFilter {
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        return super.onLoginSuccess(token, subject, request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        return super.onLoginFailure(token, e, request, response);
    }

    //未登录访问资源时进入该方法
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
//        System.out.println("跳转到登录页面");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(ResultBean.unAuthentication()));
        writer.flush();
        writer.close();
    }

    //过滤掉options请求
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        boolean allow = super.isAccessAllowed(request, response, mappedValue);
//       查看被拦截请求的请求类型，若是options请求则放行
        if (!allow) {
//            获取请求的类型
            String method = WebUtils.toHttp(request).getMethod();
            if (method.equalsIgnoreCase("options")) {
                return true;
            }
        }

        return allow;
    }
}
